<script setup>
import { ref } from 'vue'
import {
  projectTypePageQueryService,
  deleteProjectTypeService,
  updateProjectTypeStatusService
} from '@/api/project.js'
import {
  Search,
  Refresh,
  Edit,
  Delete,
  DCaret,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue'
import ProjectTypeEdit from './components/ProjectTypeEdit.vue'
import { useUserStore } from '@/stores'

// 获取用户角色
const userStore = useUserStore()
const userRole = userStore.user.role

const projectTypeList = ref([]) // 服务项目类型列表
const total = ref(0) // 总条数
const loading = ref(false) // loading状态

// 请求参数
const params = ref({
  pageNum: 1, // 当前页码
  pageSize: 10, // 每页条数
  orderBy: 'update_time', // 排序字段
  isAsc: false, // 是否升序
  projectTypeName: null, // 服务项目类型名称
  status: null // 类型状态
})

// 基于params参数，获取服务项目类型列表
const getProjectTypeList = async () => {
  loading.value = true
  const res = await projectTypePageQueryService(params.value)
  projectTypeList.value = res.data.data.list
  total.value = res.data.data.total
  loading.value = false
}
getProjectTypeList()

// 处理分页逻辑
const onPageSizeChange = (size) => {
  params.value.pageNum = 1
  params.value.pageSize = size
  getProjectTypeList()
}
const onPageNumChange = (page) => {
  params.value.pageNum = page
  getProjectTypeList()
}

// 处理排序逻辑
const handleSort = (field) => {
  if (params.value.isAsc === false && params.value.orderBy === field) {
    // 如果当前已经降序，则重置排序
    params.value.orderBy = null
    params.value.isAsc = null
  } else if (params.value.orderBy === field) {
    // 如果当前已经是按该字段排序，则切换升序/降序
    params.value.isAsc = !params.value.isAsc
  } else {
    // 如果是第一次点击该字段，则默认升序
    params.value.orderBy = field
    params.value.isAsc = true
  }
  // 重新获取数据
  getProjectTypeList()
}

// 获取排序图标
const getSortIcon = (field) => {
  if (params.value.orderBy === field) {
    return params.value.isAsc ? CaretTop : CaretBottom
  }
  return DCaret
}

// 搜索逻辑
const handleSearch = () => {
  params.value.pageNum = 1
  getProjectTypeList()
}

// 重置逻辑
const handleReset = () => {
  params.value = {
    ...params.value, // 保留其他属性
    pageNum: 1,
    projectTypeName: null,
    status: null
  }
  getProjectTypeList()
}

const projectTypeEditRef = ref()
// 新增逻辑
const handleAdd = () => {
  projectTypeEditRef.value.open({})
}

// 编辑逻辑
const handleEdit = (row) => {
  projectTypeEditRef.value.open(row)
}

// 删除逻辑
const handleDelete = async (row) => {
  await ElMessageBox.confirm('是否确认删除该服务项目类型？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await deleteProjectTypeService(row.id)
  ElNotification({
    title: '删除成功',
    type: 'success'
  })
  getProjectTypeList()
}

// 修改服务项目类型状态
const handleStatusChange = async (row) => {
  try {
    await updateProjectTypeStatusService(row.status, row.id)
    ElNotification({
      title: `${row.status}服务项目类型状态成功`,
      type: 'success'
    })
  } catch (error) {
    row.status = row.status === '启用' ? '禁用' : '启用'
  }
}
</script>

<template>
  <page-container title="服务项目类型管理">
    <template #extra>
      <el-button
        v-if="['管理员', '店长'].includes(userRole)"
        type="primary"
        plain
        @click="handleAdd"
        >新增服务项目类型</el-button
      >
    </template>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item label="服务项目类型名称:"
        ><el-input v-model="params.projectTypeName" placeholder="请输入"
      /></el-form-item>
      <el-form-item label="类型状态:">
        <el-select v-model="params.status" style="width: 100px">
          <el-option label="禁用" value="禁用"></el-option>
          <el-option label="启用" value="启用"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleSearch"></el-button>
        <el-button type="default" :icon="Refresh" @click="handleReset"></el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table
      class="tb"
      :data="projectTypeList"
      v-loading="loading"
      :row-style="{ height: '50px' }"
    >
      <el-table-column prop="id" label="服务项目类型ID">
        <template #header>
          <span>服务项目类型ID</span>
          <el-icon @click="handleSort('id')">
            <component :is="getSortIcon('id')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="类型名称" />
      <el-table-column prop="status" label="类型状态">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            active-value="启用"
            inactive-value="禁用"
            active-text="启用"
            inactive-text="禁用"
            @click="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #header>
          <span>创建时间</span>
          <el-icon @click="handleSort('create_time')">
            <component :is="getSortIcon('create_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
        <template #header>
          <span>更新时间</span>
          <el-icon @click="handleSort('update_time')">
            <component :is="getSortIcon('update_time')" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column v-if="['管理员', '店长'].includes(userRole)" label="操作" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            plain
            size="small"
            @click="handleEdit(row)"
          ></el-button>
          <el-button
            type="danger"
            :icon="Delete"
            plain
            size="small"
            @click="handleDelete(row)"
          ></el-button>
        </template>
      </el-table-column>
      <!-- 空数据提示 -->
      <template #empty>
        <el-empty description="没有数据"></el-empty>
      </template>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="params.pageNum"
      v-model:page-size="params.pageSize"
      :page-sizes="[5, 10, 20, 50, 100]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onPageSizeChange"
      @current-change="onPageNumChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </page-container>
  <!-- 抽屉 -->
  <project-type-edit ref="projectTypeEditRef" @success="handleReset" />
</template>

<style lang="scss" scoped>
.tb {
  border-radius: 10px;
  box-shadow: 0 5px 10px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
</style>
